import { createRouter, createWebHistory } from 'vue-router';
import Login from '../components/Login.vue';
import TodoApp from '../components/TodoApp.vue';
import { useAuthStore } from '../stores/auth';

const authStore = useAuthStore();

export const routes = [
  {
    path: '/',
    name: 'TodoApp',
    component: TodoApp,
    meta: { requiresAuth: true },
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (!authStore.user) {
      next({
        path: '/login',
        query: { redirect: to.fullPath },
      });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;

